package cn.yunyichina.provider.framework.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLDecoder;

/**
 * Created by JoeZ on 2016/10/14.
 */
public class HttpUtils {

    private static final Logger logger = LoggerFactory.getLogger(HttpUtils.class);

    /**
     * 下载
     * @param httpUrl
     * @return
     */
    public static boolean httpDownload (String httpUrl,String fileName){
        logger.info(">>>下载文件：" + httpUrl);
        // 下载网络文件
        int bytesum = 0;
        int byteread = 0;

        URL url = null;
        try {
            url = new URL(httpUrl);
        } catch (MalformedURLException e1) {
            // TODO Auto-generated catch block
            logger.error("[HttpUtils.httpDownload]",e1);
            return false;
        }

        FileOutputStream fs = null;
        InputStream inStream = null;
        URLConnection conn = null;

        try {
            conn = url.openConnection();
            inStream = conn.getInputStream();
            fs = new FileOutputStream(fileName);

            byte[] buffer = new byte[1204];
            while ((byteread = inStream.read(buffer)) != -1) {
                bytesum += byteread;
                fs.write(buffer, 0, byteread);
            }
            logger.info(">>>文件下载完成，保存路径：" + fileName);
            return true;
        } catch (FileNotFoundException e) {
            logger.error("[HttpUtils.httpDownload]",e);
            return false;
        } catch (IOException e) {
            logger.error("[HttpUtils.httpDownload]",e);
            return false;
        } finally {
            try {
                if(fs != null){
                    fs.close();
                }
                if(inStream != null){
                    inStream.close();
                }
                if (conn != null){
                    conn = null;
                }
            } catch (IOException e) {
               logger.error("[HttpUtils.httpDownload]",e);
            }
        }
    }
}
